package feishu

import (
	"bytes"
	"encoding/json"
	"gitee.com/huerbiao/robot/pkg/logger"
	"github.com/spf13/cast"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var httpClient *http.Client

func init() {
	var seconds time.Duration = 2000

	httpClient = &http.Client{
		Timeout: time.Duration(seconds * time.Millisecond), //超时时间2s
	}
}

func writelog(file, uri string, params map[string]interface{}, err error) {
	params["apiuri"] = uri
	params["error"] = err.Error()

	logger.Warn(nil, file, params)
}

func ExecCurlGet(strUrl string, mapHeaderParams map[string]string) (strJson string, err error) {

	req, err := http.NewRequest("GET", strUrl, nil)
	if err != nil {
		writelog("curl", strUrl, map[string]interface{}{"_msg": "new request"}, err)
		return
	}

	req.Header.Add("cache-control", "no-cache")
	if len(mapHeaderParams) > 0 {
		for hKey, hval := range mapHeaderParams {
			if hKey != "accept-encoding" {
				req.Header.Set(hKey, hval)
			}
		}
	}

	res, err := httpClient.Do(req)
	if err != nil {
		writelog("curl", strUrl, map[string]interface{}{"_msg": "do request"}, err)
		return
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		writelog("curl", strUrl, map[string]interface{}{"_msg": "readbody"}, err)
		return
	}

	return string(body), nil
}

func ExecCurlPost(strUrl string, mapParams map[string]interface{}, mapHeaderParams map[string]string, strContentType string) (strJson string, err error) {
	//添加header信息
	strHeaderContentType := "application/x-www-form-urlencoded"

	var payload io.Reader
	switch strContentType {
	case "urlencoded":
		strHeaderContentType = "application/x-www-form-urlencoded"
		mapQuery := EncodeParams(mapParams)
		payload = strings.NewReader(mapQuery)

	case "json":
		strHeaderContentType = "application/json"
		post, _ := json.Marshal(mapParams)
		payload = bytes.NewBuffer([]byte(string(post)))
	}

	//发送Post请求
	req, err := http.NewRequest("POST", strUrl, payload)
	if err != nil {
		mapParams["_msg"] = "new request"
		writelog("curl", strUrl, mapParams, err)
		return
	}

	req.Header.Add("content-type", strHeaderContentType)
	req.Header.Add("cache-control", "no-cache")

	if len(mapHeaderParams) > 0 {
		for hKey, hval := range mapHeaderParams {
			if hKey != "accept-encoding" {
				req.Header.Set(hKey, hval)
			}
		}
	}

	res, err := httpClient.Do(req)
	if err != nil {
		mapParams["_msg"] = "do request"
		writelog("curl", strUrl, mapParams, err)
		return
	}

	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		mapParams["_msg"] = "readbody"
		writelog("curl", strUrl, mapParams, err)
		return
	}

	return string(body), nil
}

// 参数 encode
func EncodeParams(params map[string]interface{}) string {
	paramsData := url.Values{}

	for k, v := range params {
		paramsData.Set(k, cast.ToString(v))
	}
	return paramsData.Encode()
}
